package net.comm.util;



import java.beans.XMLDecoder;

import java.beans.XMLEncoder;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.charset.Charset;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Date;

import java.util.List;

import java.util.Random;

import java.util.ResourceBundle;

import java.util.StringTokenizer;

import java.util.regex.Matcher;

import java.util.regex.Pattern;



import javax.servlet.ServletRequest;

import javax.servlet.http.HttpServletRequest;



import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;



public class ExtStr 

{

	public final static String SWAPTYPE_SET = "set";

	public final static String SWAPTYPE_GET = "get";



	public ExtStr()

	{

	}

	

	

	public static String generateRandomString(int stringLength)

	{

		Random random=new Random();

		int code=random.nextInt(stringLength);

		return code+"";

	}



	/**

	 * ?????��????��??expStr表达�??????????str�?�?(str???大�???????��??)

	 * 

	 * @param expStr

	 *            String �???��?????表达�?

	 * @param str

	 *            Str ???�???��?????�?�?

	 * @return String ??????�??????��????????表达�?

	 */

	public static String trimChr(String expStr, String str)

	{

		String retu = expStr;

		if (expStr.length() == 0)

		{

			return retu;

		}

		if (retu.substring(0,str.length()).equals(str))

		{

			retu = retu.substring(retu.indexOf(str) + str.length(),retu

					.length());

		}

		if (retu.substring(retu.length() - str.length()).equals(str))

		{

			retu = retu.substring(0,retu.length() - str.length());

		}

		return retu;

	}



	/**

	 * ?????��?????�?表达�?象�????��????��??�?�?�? �?�?�?exp="myName=wzs,myvale=1000";

	 * getValue(exp,"myName=",",")�????�?�?"wzs"

	 * 

	 * @param exp

	 *            String

	 * @param val

	 *            String

	 * @param splitStr

	 *            String

	 * @return String

	 */

	public static String getValue(String exp, String val, String splitStr)

	{

		if (splitStr.trim().length() == 0)

		{

			return exp;

		}

		else if (val.trim().length() == 0)

		{

			return exp;

		}

		String retu = exp;

		StringTokenizer st = new StringTokenizer(exp,splitStr);

		while (st.hasMoreElements())

		{

			String tmp = st.nextToken();

			if (tmp.indexOf(val) > -1)

			{

				retu = tmp.substring(tmp.indexOf(val

						.substring(val.length() - 1)) + 1);

				break;

			}

		}

		return retu;

	}



	/**

	 * ?????��?????�?表达�?象�????��????��??�?�?�? �?�?�?String

	 * exp="myName=wzs,myvale=1000,myage=29,mysex=???";

	 * getValue(exp,"myage=",",",2[�?�?�?�????�?�?fromIndex�?�?�????�?xxx=nnn�?�????表达�?])�????�?�?"29"

	 * 

	 * @param exp

	 *            String ?????��?��??表达

	 * @param val

	 *            String ?????��?��?????�?

	 * @param splitStr

	 *            String ?????��??�?

	 * @param fromIndex

	 *            int �?exp�????�????�?xxx=nn???�?�????�?

	 * @return String ??????�????xxx=nn�?�?形�?????nn??????

	 */

	public static String getValue(String exp, String val, String splitStr, int fromIndex)

	{

		if (splitStr.trim().length() == 0)

		{

			return exp;

		}

		else if (val.trim().length() == 0)

		{

			return exp;

		}

		String retu = exp;

		StringTokenizer st = new StringTokenizer(exp,splitStr);

		int i = 0;

		while (st.hasMoreElements())

		{

			String tmp = st.nextToken();

			if (i >= fromIndex)

			{

				if (tmp.indexOf(val) > -1)

				{

					retu = tmp.substring(tmp.indexOf("=") + 1);

					break;

				}

			}

			i++;

		}

		return retu;

	}



	/**

	 * ?????��???????��??串�????��??(�?�????�?java�????String.split()????????��?????�?String.split()?????????","??��??�?�?�???????)

	 * 

	 * @param expStr

	 *            String ?????��??表达�?�?

	 * @param splitStr

	 *            String ?????��??�?�?�?

	 * @return String[]??????�????�?�?�?串�?��?? �?�?�?String a="1@2@3";String[]

	 *         as=ExtStr.split(a,"@");�????as[0]="1";as[1]="2"...

	 */

	public static String[] split(String expStr, String splitStr)

	{

		StringTokenizer st = new StringTokenizer(expStr,splitStr);

		String retu[] = new String[st.countTokens()];

		int i = 0;

		while (st.hasMoreElements())

		{

			retu[i] = st.nextToken();

			i++;

		}

		return retu;

	}



	/**

	 * ?????��????��??lObj对象�?�?�????�?????????��??vo对象�???????�?�???��?????

	 * 

	 * @param lObj

	 *            List �?�????�?�??????????�?类�??vo对象

	 * @param findVoMethodName

	 *            String

	 *            ??��?��????��??vo对象�??????��?????称�?????�????�?�?property??????称�??�?reflcet??��?�中�???��??�?private?????��????��??�????method�?

	 * @param findPropertyValue

	 *            Object ??��????��?��?��????�为�?�????类�??�??????��?�类??????Integer,String�?

	 * @return int ??????�????list?????��??�??????��??失败�????-1

	 */

	public static int indexOfVoPropertyValue(List lObj, String findVoMethodName, Object findPropertyValue)

	{

		if (lObj == null || lObj.size() == 0)

		{

			return -1;

		}

		Class cls = null;

		for (int i = 0; i < lObj.size(); i++)

		{

			Object obj = lObj.get(i);

			if (cls == null)

			{

				cls = obj.getClass();

			}

			try

			{

				Method m = cls.getMethod(findVoMethodName,null);

				Object retu = m.invoke(obj,null);

				if (retu.toString().equals(findPropertyValue.toString()))

				{

					return i;

				}

			}

			catch (SecurityException ex)

			{

				ex.printStackTrace();

			}

			catch (NoSuchMethodException ex)

			{

				ex.printStackTrace();

			}

			catch (InvocationTargetException ex)

			{

				ex.printStackTrace();

			}

			catch (IllegalArgumentException ex)

			{

				ex.printStackTrace();

			}

			catch (IllegalAccessException ex)

			{

				ex.printStackTrace();

			}

		}

		return -1;

	}



	/**

	 * ?????��????��??lObj对象�?�?�????�?????????��??vo对象�???????�?�???��?????

	 * 

	 * @param lObj

	 *            List �?�????�?�??????????�?类�??vo对象

	 * @param findVoMethodName

	 *            String

	 *            ??��?��????��??vo对象�??????��?????称�?????�????�?�?property??????称�??�?reflcet??��?�中�???��??�?private?????��????��??�????method�?

	 * @param findPropertyValue

	 *            Object ??��????��?��?��????�为�?�????类�??�??????��?�类??????Integer,String�?

	 * @param fromIndex

	 *            int �?lObj对象�?fromIndex�???��??findVoMethodName�???��?�为findPropertyValue

	 * @return int ??????�????list?????��??�??????��??失败�????-1

	 */

	public static int indexOfVoPropertyValue(List lObj, String findVoMethodName, Object findPropertyValue, int fromIndex)

	{

		if (lObj == null || lObj.size() == 0)

		{

			return -1;

		}

		Class cls = null;

		for (int i = 0; i < lObj.size(); i++)

		{

			if (i < fromIndex)

			{

				continue;

			}

			Object obj = lObj.get(i);

			if (cls == null)

			{

				cls = obj.getClass();

			}

			try

			{

				Method m = cls.getMethod(findVoMethodName,null);

				Object retu = m.invoke(obj,null);

				if (retu.toString().equals(findPropertyValue.toString()))

				{

					return i;

				}

			}

			catch (SecurityException ex)

			{

				ex.printStackTrace();

			}

			catch (NoSuchMethodException ex)

			{

				ex.printStackTrace();

			}

			catch (InvocationTargetException ex)

			{

				ex.printStackTrace();

			}

			catch (IllegalArgumentException ex)

			{

				ex.printStackTrace();

			}

			catch (IllegalAccessException ex)

			{

				ex.printStackTrace();

			}

		}

		return -1;

	}



	public static String encrypt_MD5(String str)

	{

		try

		{

			MessageDigest md = MessageDigest.getInstance("MD5");

			byte[] b = md.digest(obj2Str(str).getBytes());

			return byte2hex(b);

		}

		catch (NoSuchAlgorithmException ex)

		{

			return null;

		}

	}



	/**

	 * ?????��?????�?主页???url

	 * 

	 * @return String

	 */

	public static String getHomePageUrl(HttpServletRequest req)

	{

		String retu = req.getScheme() + "://";

		retu += req.getServerName();

		if (req.getServerPort() != 80)

		{

			retu += ":" + req.getServerPort();

		}

		retu += req.getContextPath();

		return retu;

	}



	/**

	 * ?????��????��??expstr�????�?�?�?strflag

	 * 

	 * @param expstr

	 *            String

	 * @param strflag

	 *            String

	 * @return int

	 */

	public static int getCountStr(String expstr, String strflag)

	{

		int retu = 0;

		int fromIndex = 0;

		int i = expstr.indexOf(strflag,fromIndex);

		while (i >= 0)

		{

			retu++;

			fromIndex = i + strflag.length();

			i = expstr.indexOf(strflag,fromIndex);

		}

		return retu;

	}



	/**

	 * ?????��????????servlet forward??��??�?对路�?

	 * 

	 * @param subrootUrl

	 *            String �?????????��??�????称�??�?�?�?�????许使??��?��?�路�?�?

	 * @return String ??????�????�?�?�?对路�?

	 *         �?�?�????设�??????????��??�????http://localhost:8080/rootDir,rootDir???�?�???��??aDir,bDir�????�?

	 *         �????servlet�????�?�?�???��?????�?

	 *         forward()�?bDir�???��??�?�?b.jsp???使�??req.getRequestDispatcher(ExtStr.makeServletUrl(req,"bDir/b.jsp"));

	 *         forward()�????�?�?servlet(otherServlet.do)???使�??req.getRequestDispatcher(ExtStr.makeServletUrl(req,"otherServlet.do"));

	 */

	public static String makeServletUrl(HttpServletRequest req, String subrootUrl)

	{

		int cnt = getCountStr(req.getRequestURI(),"/") - 2;

		String retu = "";

		for (int i = 0; i < cnt; i++)

		{

			retu += "../";

		}

		retu += subrootUrl;

		return retu;

	}



	/**

	 * ?????��??�?�???�转�?�?�?

	 * 

	 * @param b

	 *            byte[]

	 * @return String

	 */

	public static String byte2hex(byte[] b)

	{

		String hs = "";

		String stmp = "";

		for (int n = 0; n < b.length; n++)

		{

			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));

			if (stmp.length() == 1)

			{

				hs += "0" + stmp;

			}

			else

			{

				hs += stmp;

			}

		}

		return hs.toLowerCase();

	}



	/**

	 * ?????��?????expStr表达�?�?replStr�?串�?��?��??newStr

	 * 

	 * @param expStr

	 *            String

	 * @param replStr

	 *            String

	 * @param newStr

	 *            String

	 * @return String

	 */

	public static String replace(String expStr, String replStr, String newStr)

	{

		StringBuffer butmp = new StringBuffer(expStr);

		int startIndex = butmp.indexOf(replStr);

		int endIndex = startIndex + replStr.length();

		int newStrLen = newStr.length();

		while (startIndex >= 0)

		{

			butmp.replace(startIndex,endIndex,newStr);

			startIndex = butmp.indexOf(replStr,startIndex + newStrLen);

			endIndex = startIndex + replStr.length();

		}

		return butmp.toString();

	}



	/**

	 * ?????��?????expStr表达�?�?replStr�?串�?��?��??newStr�?replStr?????��?��??表达�??????????�?�?

	 * 

	 * @param expStr

	 *            String

	 * @param replStr

	 *            String

	 * @param newStr

	 *            String

	 * @return String ??????�??????��?��?????�?串�??失败�????�????

	 */

	public static String replaceRegEx(String expStr, String replStr, String newStr)

	{

		String retu = expStr;

		Pattern p = Pattern.compile(replStr);

		Matcher m = p.matcher(expStr);

		retu = m.replaceAll(newStr);

		return retu;

	}

	/**

	 * ?????��?????expStr表达�?�?replStr�?串�?��?��??newStr

	 * 

	 * @param expStr

	 *            String

	 * @param replStr

	 *            String

	 * @param newStr

	 *            String

	 * @param fromIndex

	 *            int �?expStr�????�?fromIndex??��?��?��??�?fromIndex�?0�?�?�?

	 * @return String

	 */

	public static String replace(String expStr, String replStr, String newStr, int fromIndex)

	{

		StringBuffer butmp = new StringBuffer(expStr);

		int startIndex = butmp.indexOf(replStr,fromIndex);

		int endIndex = startIndex + replStr.length();

		int newStrLen = newStr.length();

		while (startIndex >= 0)

		{

			butmp.replace(startIndex,endIndex,newStr);

			startIndex = butmp.indexOf(replStr,startIndex + newStrLen);

			endIndex = startIndex + replStr.length();

		}

		return butmp.toString();

	}



	/**

	 * ?????��?????�????�?串转???base64�?�?

	 * 

	 * @param str

	 *            String

	 * @return String ?????????str�???��??base64�????,失败�????null

	 */

	public static String string2Base64(String str)

	{

		if (str.length() == 0)

		{

			return null;

		}

		BASE64Encoder base64en = new BASE64Encoder();

		String rt=base64en.encodeBuffer(str.getBytes());

//		??��?�转??��?��?��??base64�?串太??��?????\r\n�?�???��?????�???��??

		rt=ExtStr.replace(rt,"\r", "");

		rt=ExtStr.replace(rt,"\n", "");

		return rt;

	}



	/**

	 * ?????��?????base64�?串�?????

	 * 

	 * @param base64str

	 *            String

	 * @return String ??????�????�?失败�????null

	 */

	public static String base642String(String base64str)

	{

		BASE64Decoder base64de = new BASE64Decoder();

		if (base64str.length() == 0)

		{

			return null;

		}

		try

		{

			return new String(base64de.decodeBuffer(base64str));

		}

		catch (IOException ex)

		{

			return null;

		}

	}



	/**

	 * ?????��?????base64�?串�?????

	 * 

	 * @param f

	 *            File

	 * @return String

	 */

	public static String file2base64(File f)

	{

		try

		{

			InputStream fis = new FileInputStream(f);

			byte[] fb = new byte[(int) f.length()];

			fis.read(fb);

			fis.close();

			BASE64Encoder base64en = new BASE64Encoder();

			return base64en.encode(fb);

		}

		catch (IOException ex)

		{

			ex.printStackTrace();

			return null;

		}

	}



	/**

	 * ?????��?????�???????�?�?mapUrl??��??�?系�??�????�????�?�?�?�?

	 * 

	 * @param req

	 *            ServletRequest

	 * @param mapUrl

	 *            String

	 * @return String ??????�??????�硬??????�????�?�?�?失败�????null

	 */

	public static String getServletMappingPath(ServletRequest req, String mapUrl)

	{

		if (req == null || mapUrl == null)

		{

			return null;

		}

		if (mapUrl.trim().length() == 0)

		{

			return null;

		}

		return ((HttpServletRequest) req).getSession().getServletContext()

				.getRealPath(mapUrl);

	}



	/**

	 * ?????��?????�???????�?�?mapUrl??��??�?系�??�????�????�?�?�?�?

	 * 

	 * @param req

	 *            HttpServletRequest

	 * @param mapUrl

	 *            String

	 * @return String ??????�??????�硬??????�????�?�?�?失败�????null

	 */

	public static String getServletMappingPath(HttpServletRequest req, String mapUrl)

	{

		if (req == null || mapUrl == null)

		{

			return null;

		}

		if (mapUrl.trim().length() == 0)

		{

			return null;

		}

		return req.getSession().getServletContext().getRealPath(mapUrl);

	}



	/**

	 * ?????��?????obj对象�???��??�?串�??�????obj???null???�????""�?

	 * 

	 * @param obj

	 *            Object

	 * @return String ?????????obj�????�?串�????????�????""

	 */

	public static String obj2Str(Object obj)

	{

		if (obj == null)

		{

			return "";

		}

		return obj.toString().trim();

	}



	/**

	 * ?????��????��??doubleLanguageStr????????????�???????�???��?????�?�?�????�???????2�?�???????�?�?

	 * 

	 * @param doubleLanguageStr

	 *            String

	 * @return boolean

	 */

	public static boolean isDoubleByte(String doubleLanguageStr)

	{

		boolean retu = false;

		int len1 = obj2Str(doubleLanguageStr).length();

		if (len1 == 0)

		{

			return retu;

		}

		byte[] bs = doubleLanguageStr.getBytes();

		int len2 = bs.length;

		if (len1 < len2)

		{

			retu = true;

		}

		return retu;

	}

	/**

	 * �?obj(vo)对象�?�??????????xml???�?

	 * @param obj vo对象

	 * @param xmlname �?�???????件�??�?

	 */

	public static void object2Xml(Object obj,String xmlname)

	{

		BufferedOutputStream bos=null;

		try

		{

			bos = new BufferedOutputStream(new FileOutputStream(xmlname));

			XMLEncoder xec=new XMLEncoder(bos);

			xec.writeObject(obj);

			xec.close();

		}

		catch (FileNotFoundException e)

		{

			e.printStackTrace();

		}

	}

	/**

	 * �?xml???件转??��??vo对象

	 * @param xmlname �???��??xml???�?

	 * @return?????????�????vo对象�?失败�????null

	 */

	public static Object xml2Object(String xmlname)

	{

		BufferedInputStream bis;

		try

		{

			bis = new BufferedInputStream(new FileInputStream(xmlname));

			XMLDecoder xdd=new XMLDecoder(bis);

			xdd.close();

			return xdd.readObject();

		}

		catch (FileNotFoundException e)

		{

			e.printStackTrace();

			return null;

		}

	}

	/**

	 * ???xml??��?????xmlstr??????�????对象

	 * @param xmlstr

	 * @return ??????�??????��??xmlstr??????容�??建�??�?�?对象�?失败�????null

	 */

	public static Object xmlstr2Object(String xmlstr)

	{

		try

		{

//			String xmlname=(new Date()).getTime()+".xml";

//			File f=new File(xmlname);

//			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));

//			String str=new String(xmlstr.getBytes(),"UTF-8");

//			bos.write(str.getBytes());

//			FileInputStream fis=new FileInputStream(f);			

//

//			XMLDecoder xdd=new XMLDecoder(fis);

//			xdd.close();

//			fis.close();

//			bos.close();

//			if(f.exists())

//			{

//				f.delete();

//			}

			ByteArrayInputStream bais=new ByteArrayInputStream(xmlstr.getBytes("GB2312"));

			XMLDecoder xdd=new XMLDecoder(bais);

			xdd.close();

			return xdd.readObject();

		}

		catch (Exception e)

		{

			e.printStackTrace();

			return null;

		}

	}

	/**

	 * ???obj对象�????xml??��?????�?�?

	 * @param obj

	 * @return ??????�????xml??��?????�?串�??失败�????null

	 */

	public static String object2Xmlstr(Object obj)

	{

		BufferedOutputStream bos=null;

		try

		{

			synchronized(obj)

			{

				String xmlname=(new Date()).getTime()+"";

				File f=new File(xmlname);

				bos = new BufferedOutputStream(new FileOutputStream(f));

				XMLEncoder xec=new XMLEncoder(bos);

				xec.writeObject(obj);

				xec.close();

				FileInputStream fis=new FileInputStream(f);

				byte[] b=new byte[(int)f.length()];

				fis.read(b);

//				String df=new String(retu.getBytes("UTF-8"));

//				bos.write(df.getBytes());

				bos.close();

				fis.close();

				if(f.exists())

				{

					f.delete();

				}

				f=null;

				return new String(b,"GB2312") ;

			}

		}

		catch (Exception e)

		{

			e.printStackTrace();

			return null;

		}

	}

	/**

	 * ???�?串�?��??�???��?????","?????????�?�?

	 * @param strArray �?�???��??�?串�?��??

	 * @return ??????�????�?串�??失败�????""

	 */

	public static String strArray2Str(String[] strArray)

	{

		String retu="";

		if(strArray!=null)

		{

			for (int i = 0; i < strArray.length; i++)

			{

				retu+=strArray[i]+",";

			}

			retu=ExtStr.trimChr(retu,",");

		}

		return retu;

	}

	

	public static String getLocalResourceStr(String keyName)

	{

		ResourceBundle rb=ResourceBundle.getBundle("msgResources");

		return rb.getString(keyName);

	}

	public static String getLocalResourceStr(String keyName,String resourceName)

	{

		ResourceBundle rb=ResourceBundle.getBundle(resourceName);

		return rb.getString(keyName);

	}

	/**

	 * 

	 * @param charsetName

	 * @param str

	 * @return

	 */

	public static String unicodeStr2AnyCharsetStr(String charsetName,String str)

	{

		Charset chr=Charset.forName(charsetName);

		ByteBuffer bbf=chr.encode(str);

		CharBuffer cb=chr.decode(bbf);

		return cb.toString();

	}

	/**

	 * ???str�?串�??�?�?�?�?�????大�??

	 * @param str

	 * @return

	 */

	public static String firstCharToUpperCase(String str)

	{

		String str1=str.substring(0,1).toUpperCase();

		try

		{

			return str1+str.substring(1);

		}

		finally

		{

			str1=null;

		}

	}

	/**

	 * ???str�?串�??�?�?�?�?�????�????

	 * @param str

	 * @return

	 */

	public static String firstCharToLowerCase(String str)

	{

		String str1=str.substring(0,1).toLowerCase();

		try

		{

			return str1+str.substring(1);

		}

		finally

		{

			str1=null;

		}

	}

	/**

	 * ???�?cls?????��??�????ClassPath起�???????�路�?

	 * @param cls

	 * @return

	 */

	public static String getRootClassPath(Class cls)

	{

		if(cls==null)

		{

			return null;

		}

		String path=cls.getResource("/").getPath();

		try

		{

			return path;

		}

		finally

		{

			path=null;

		}

	}

	public static void main(String[] args)

	{

		System.out.println(ExtStr.getRootClassPath(ExtStr.class));

	}

}

